﻿using System.Linq;
using MM.Data.Entity;
using MM.Services.decl;

namespace MM.Services.impl
{
    public class OperationTypeService : BaseService, IOperationTypeInterface
    {
        /// <summary>
        /// Adds the type of the operation.
        /// </summary>
        /// <param name="operationType">Type of the operation.</param>
        public void AddOperationType(OperationType operationType)
        {
            if (operationType != null) MyMoneyContext.OperationTypes.Add(operationType);
            Commit();
        }

        /// <summary>
        /// Gets the parent operation.
        /// </summary>
        /// <param name="operation">The operation.</param>
        /// <returns></returns>
        public OperationType GetParentOperation(OperationType operation)
        {
            var parent = MyMoneyContext.OperationTypes.FirstOrDefault(
                _ => operation.ParentId != null && _.OperationTypeId == operation.ParentId);
            return parent;
        }

        /// <summary>
        /// Gets all parent operation list.
        /// </summary>
        /// <returns></returns>
        public IQueryable<OperationType> GetAllParentOperationList()
        {
            var allItems = GetAllOperationTypesHierarchical();
            return allItems.Where(rootItem => rootItem.ParentId == 0 || rootItem.ParentId == null);
        }

        /// <summary>
        /// Gets all operation types hierarchical.
        /// </summary>
        /// <returns></returns>
        public IQueryable<OperationType> GetAllOperationTypesHierarchical()
        {
            return MyMoneyContext.OperationTypes;
        }
    }
}